package ch.sv7.tool.dbmanager.db.fixbuilder;

import java.util.List;

import ch.sv7.tool.dbmanager.Context;
import ch.sv7.tool.dbmanager.db.ForeignKeySchema;
import ch.sv7.tool.dbmanager.db.dialect.Dialect;
import ch.sv7.tool.dbmanager.db.difference.ForeignKeyNameDifference;
import ch.sv7.tool.dbmanager.db.difference.SchemaDifference;
import ch.sv7.tool.dbmanager.db.fix.CreateForeignKeyFix;
import ch.sv7.tool.dbmanager.db.fix.DropForeignKeyFix;
import ch.sv7.tool.dbmanager.db.fix.RenameForeignKeyFix;
import ch.sv7.tool.dbmanager.db.fix.SchemaFix;

/**
 * TODO: Document me!
 *
 * @author svt
 *
 */
public class ForeignKeyNameFixBuilder implements FixBuilder {

	public SchemaFix[] createFixes(SchemaDifference difference, Dialect dialect, Context context) {
		ForeignKeyNameDifference foreignKeyNameDifference = (ForeignKeyNameDifference)difference;
		/*
		 * Check if expected foreign key name already exists
		 */
		String expectedName = foreignKeyNameDifference.getExpectedForeignKey().getName();
		boolean expectedNameExists = false;
		List fKeys = foreignKeyNameDifference.getActualForeignKey().getTableSchema().getForeignKeys();
		for (int i=0; i<fKeys.size(); i++) {
			ForeignKeySchema fk = (ForeignKeySchema)fKeys.get(i);
			if (fk.getName().equals(expectedName)){
				expectedNameExists = true;
				break;
			}
		}
		if (expectedNameExists){
			SchemaFix dropFix = new DropForeignKeyFix(foreignKeyNameDifference.getActualForeignKey());
			SchemaFix createFix = new CreateForeignKeyFix(foreignKeyNameDifference.getExpectedForeignKey());
			return new SchemaFix[]{ dropFix, createFix };			
		} else {
			SchemaFix fix = new RenameForeignKeyFix(foreignKeyNameDifference.getActualForeignKey(), 
					foreignKeyNameDifference.getExpectedForeignKey());
			return new SchemaFix[]{ fix };
		}
	}

}
